package org.ne.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.ne.springboot.interceptor.MinioService;
import org.ne.springboot.service.ImageCheckService;
import org.ne.springboot.utils.MultipartFileDto;
import org.ne.springboot.utils.PaperHandleUtils.CommonUtils.WordUtils;
import org.ne.springboot.utils.PaperHandleUtils.PaperContentCheckUtils.ImageSparkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import java.io.*;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;

import org.apache.http.entity.ContentType;

/**
 * @author luolinila
 * @date 2025/9/2 23:54
 */
@Service
public class ImageFormatServiceImpl implements ImageCheckService {

    @Autowired
    private MinioService minioService;

    //图片标题检查
    @Override
    public List<String> checkImageTitle(XWPFDocument doc) throws IOException {
        List<String> results = new ArrayList<>();
        List<HashMap<String, Object>> list =  getImageMap(doc);
        HashMap<String, Object> imageTrueTitle = list.get(0);
        HashMap<String, Object> imageTitle = list.get(1);
        HashMap<String, Object> image = list.get(2);

        for(int i = 0; i <  imageTrueTitle.size(); i++) {
            String imageName = "图片" + (i + 1);
            XWPFParagraph paragraph = (XWPFParagraph) imageTitle.get(imageName);
            String result = imageName + "： " + paragraph.getText() + "\n";
            boolean haveIssues = false;
            String title =  paragraph.getText().trim();


            if (!title.startsWith((String) imageTrueTitle.get(imageName))) {
                haveIssues = true;
                String res = "图片标题应为" +  (String) imageTrueTitle.get(imageName) + "\n";
                result += res;
            }

            //判断样式是否为 宋体 五号 居中
            // 检查是否为宋体
            boolean isSimSun = WordUtils.checkFontFamily(paragraph);
            // 检查是否为五号字
            boolean isSize5 = WordUtils.checkFontSize(paragraph);
            // 检查是否居中
            boolean isCentered = WordUtils.checkAlignment(paragraph);
            if (!isSimSun) {
                haveIssues = true;
                String res = "字体应为宋体\n";
                result += res;
            }
            if(!isSize5) {
                haveIssues = true;
                String res = "字体大小应为五号\n";
                result += res;
            }
            if (!isCentered) {
                haveIssues = true;
                String res = "段落应居中\n";
                result += res;
            }
            if (!haveIssues) {
                String res = "图片标题正确\n";
                result += res;
            }
            results.add(result);
        }
        if (imageTitle.size() != image.size()) {
            if (imageTitle.size() > image.size()) {
                String res = "有" + (imageTitle.size() - image.size()) + "个标题无法找到对应图片\n";
                results.add(res);
            }else {
                String res = "有" + (image.size() - imageTitle.size()) + "张图片无法找到对应标题\n";
                results.add(res);
            }
        }
        return results;
    }

    public List<String> getImageTitles(XWPFDocument file) throws IOException {
        //获取所有图片标题
        List<String> imageTitles = new ArrayList<>();
        //第 a 段 第 b 张图
        List<HashMap<String, Object>>  list =  getImageMap(file);
        HashMap<String, Object> imageTitle = list.get(1);
        for (int i = 0; i < imageTitle.size(); i++) {
            String imageName = "图片" + (i + 1);
            XWPFParagraph paragraph = (XWPFParagraph) imageTitle.get(imageName);
            String title =  paragraph.getText().trim();
            imageTitles.add(title);
        }
        return imageTitles;
    }

    @Override
    public List<String> checkImageContent(XWPFDocument file) throws IOException {
        List<String> results = new ArrayList<>();
        List<String> imageUrls = getImageFiles(file);
        File f = new File("src/main/resources/images");
        List<String> titles = getImageTitles(file);
        for (int i = 0; i < titles.size(); i++) {
            Map resMap = JSONObject.toJavaObject(JSON.parseObject(imageAiCheck(imageUrls.get(i), titles.get(i))), Map.class);
            results.add("图片" + (i + 1) + "\n" + titles.get(i) + "\n" + resMap.get("cod") + "\n" + resMap.get("reason") + "\n" + resMap.get("suggest") + "\n");
        }

        return results;
    }

    private String imageAiCheck(String imageUrl, String imageTile) {
        ImageSparkClient  imageSparkClient = new ImageSparkClient();
        imageSparkClient.setModel("imageSpark");

        HashMap<String, Object> format = new HashMap<>();
        format.put("cod", "图片与标题是否相符");
        format.put("reason", "原因");
        format.put("suggest", "修改建议");
        imageSparkClient.setFormat(format);

        HashMap<String, String> inputMap = new HashMap<>();
        inputMap.put("imageTitle", imageTile);

        return imageSparkClient.processRequest(imageUrl, inputMap).get("answer").toString();
    }

    private List<String> getImageFiles(XWPFDocument file) throws IOException {
        List<XWPFPictureData> allPictures = file.getAllPictures();
        List<String> files = new ArrayList<>();
        for (int i = 0; i < allPictures.size(); i++) {
            XWPFPictureData picture = allPictures.get(i);
            byte[] pictureData = picture.getData();
            String base64 = Base64.getEncoder().encodeToString(pictureData);
            files.add(base64);
        }
        return files;
    }

    private List<MultipartFile> allTypeToMultipartFile(List<File> list) throws IOException {
        List<MultipartFile> results = new ArrayList<>();
        for (File file : list) {
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MultipartFileDto(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.getMimeType(), fileInputStream);
            results.add(multipartFile);
        }
        return results;
    }

    private List<String> updateMultipartFile(List<MultipartFile> list) {
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile multipartFile : list) {
            String path = minioService.uploadFile(multipartFile);
            imageUrls.add(path);
        }
        return imageUrls;
    }

    private List<HashMap<String, Object>> getImageMap(XWPFDocument file) throws IOException {
        List<String> headings = WordUtils.findHeadingOne(file);
        HashMap<String, Object> imageTrueTitle = new HashMap<>();
        HashMap<String, Object> imageTitle = new HashMap<>();
        HashMap<String, Object>  image = new HashMap<>();

        int count = 0;
        int a = 0, b = 0;
        for (XWPFParagraph paragraph : file.getParagraphs()) {
            String text =  paragraph.getText().trim();
            if(paragraph.getStyle() != null && headings.contains(text)) {
                a++;
                b = 0;
            }
            if(text.startsWith("图")) {
                b++;
                count++;
                imageTrueTitle.put("图片" +  count, "图" + a + "." + b);
                imageTitle.put("图片" +  count, paragraph);
            }
        }
        count = 0;
        for (XWPFPictureData picture : file.getAllPictures()) {
            count++;
            image.put("图片" + count, picture);
        }
        List<HashMap<String, Object>> results = new ArrayList<>();
        results.add(imageTrueTitle);
        results.add(imageTitle);
        results.add(image);
        return results;
    }

}
